package com.wzxy.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.wzxy.dao.IStudentDao;
import com.wzxy.model.Student;

//学生业务逻辑接口的实现类
@Repository("studentDao")
public class StudentDaoImpl implements IStudentDao{
	@Resource
	protected SessionFactory sessionFactory;
 
	public Session getSession() {
		return sessionFactory.openSession();
	}
 
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Student> queryAllStudents() {
		Session session = this.getSession();
		List<Student> list = null;
		String hql = "from Student";
		Query query = session.createQuery(hql);
		list = query.list();
		session.close();
		return list;
	}

	@Override
	public Student queryStudentById(String sid) {
		Session session = this.getSession();
		String hql = "from Student where sid = ?";
		Query query = session.createQuery(hql);
		query.setString(0, sid);
		return (Student) query.uniqueResult();
	}

	@Override
	public void addStudent(Student s) {
		this.getSession().save(s);
	}

	@Override
	public boolean updateStudent(Student s) {
		Session session = this.getSession();
        String hql = "update Student set sname=? where sid=?";  
        Query query = session.createQuery(hql);  
        query.setString(0, s.getSname());  
        query.setInteger(1, s.getSid());  
        return query.executeUpdate()>0; 
	}

	@Override
	public boolean deleteStudent(String sid) {
		Session session = this.getSession();
        String hql = "delete from Student where sid=?";  
        Query query = session.createQuery(hql);  
        query.setString(0, sid); 
        return query.executeUpdate()>0; 
	}
	
}
